from flask import Flask, jsonify,request
from flask_cors import CORS
import random
import configparser
from datetime import datetime, timedelta
from main import EtcModel,read_excel
import os

app = Flask(__name__)
CORS(app)  # 启用CORS以允许前端访问
config = configparser.ConfigParser()
eModel= EtcModel()
rankcount = []
current_speed=0
current_flow=0
pre_speed=0
pre_flow=0
pre_rank=0
pre_time=''

def init_data(data_type):
    if data_type == 'svr_data':
        data_up = read_excel('test_up')
        speed_up = data_up['speed'].transpose().tolist()[0]
        flow_up = data_up['flow'].transpose().tolist()[0]
        svr_data = list(zip(speed_up, flow_up))
        ret_data = svr_data[:3]
    else:
        data_down = read_excel('test_down')
        speed_down = data_down['speed'].transpose().tolist()[0]
        flow_down = data_down['flow'].transpose().tolist()[0]
        lstm_data = list(zip(speed_down, flow_down))
        ret_data = lstm_data[:100]
    return ret_data

def read_ini(config, param_name):
    config.read('data.ini')
    param_str = config.get('Data', param_name)
    param_list = eval(param_str)
    return param_list

def write_ini(config, param_name,param):
    config.read('data.ini')
    param_str = str(param)

    if 'Data' in config:
        config.set('Data', param_name, param_str)  # 更新现有的section和key
    else:
        config.add_section('Data')  # 如果section不存在，则添加
        config.set('Data', param_name, param_str)  # 添加新的key-value
    with open('data.ini', 'w') as configfile:
        config.write(configfile)

    return True

def update_congestion(timestamp,pre_congestion):
    global pre_time
    congestion_dict = read_ini(config,'congestion_dict')
    dt = datetime.fromtimestamp(timestamp)
    pre_time = dt.strftime('%m-%d %H:%M:%S')
    dt_with_delta = dt + timedelta(minutes=5)
    formatted_time = dt_with_delta.strftime('%m-%d %H:%M')
    if len(congestion_dict) >= 12:
        first_key = next(iter(congestion_dict))
        congestion_dict.pop(first_key)
    congestion_dict[formatted_time] = pre_congestion
    write_ini(config,'congestion_dict',congestion_dict)
def update_speed(timestamp,pre_speed):
    speed_dict = read_ini(config, 'speed_dict')
    dt = datetime.fromtimestamp(timestamp)
    formatted_time = dt.strftime('%m-%d %H:%M:%S')
    if len(speed_dict) >= 12:
        first_key = next(iter(speed_dict))
        speed_dict.pop(first_key)
    speed_dict[formatted_time] = pre_speed
    write_ini(config, 'speed_dict', speed_dict)
def update_flow(timestamp,pre_flow):
    flow_dict = read_ini(config, 'flow_dict')
    dt = datetime.fromtimestamp(timestamp)
    formatted_time = dt.strftime('%m-%d %H:%M:%S')
    if len(flow_dict) >= 12:
        first_key = next(iter(flow_dict))
        flow_dict.pop(first_key)
    flow_dict[formatted_time] = pre_flow
    write_ini(config, 'flow_dict', flow_dict)


@app.route('/updatedata', methods=['POST'])
def update_data():
    global current_speed,current_flow,pre_speed,pre_flow,pre_rank
    timestamp = request.json.get("timestamp")
    up_speed = request.json.get("up_speed")
    up_flow = request.json.get("up_flow")
    down_speed = request.json.get("down_speed")
    down_flow = request.json.get("down_flow")

    current_speed = down_speed
    current_flow = down_flow

    svr_data = read_ini(config,'svr_data')
    svr_data = svr_data[1:]
    svr_data.append((up_speed,up_flow))

    lstm_data = read_ini(config, 'lstm_data')
    lstm_data = lstm_data[1:]
    lstm_data.append((down_speed, down_flow))
    write_ini(config,'svr_data',svr_data)
    write_ini(config, 'lstm_data', lstm_data)

    fit_svr_data = eModel.fit_scaler('svr_data',svr_data)
    fit_lstm_data = eModel.fit_scaler('lstm_data', lstm_data)

    pred_speed,pred_flow,pred_rank = eModel.predict(timestamp,fit_svr_data,fit_lstm_data)
    update_congestion(timestamp = timestamp,pre_congestion=pred_rank)
    update_speed(timestamp=timestamp, pre_speed=pred_speed)
    update_flow(timestamp=timestamp, pre_flow=pred_flow*2)
    rankcount.append(pred_rank)
    pre_speed = pred_speed
    pre_flow = pred_flow
    pre_rank = pred_rank
    return jsonify({"status": "success", "message": "Data updated successfully"})

@app.route('/congestion')
def get_congestion_data():
    congestion_dict = read_ini(config, 'congestion_dict')
    times = list(congestion_dict.keys())

    values = list(congestion_dict.values())

    data = {
        'times': times,
        'values': values
    }

    return jsonify(data)


@app.route('/rankcount')
def get_rankcount_data():
    data = []  # 使用列表存储每个i的数据
    for i in set(rankcount):
        count = rankcount.count(i)
        data.append({'name': str(i), 'value': count})
    return jsonify(data)


@app.route('/speedflow')
def get_speedflow_data():
    speed_dict = read_ini(config, 'speed_dict')
    flow_dict = read_ini(config, 'flow_dict')
    times = list(flow_dict.keys())
    speed = list(speed_dict.values())
    flow = list(flow_dict.values())
    data = {
        'times': times,
        'speed': speed,
        'flow': flow
    }

    return jsonify(data)


@app.route('/current_data')
def get_current_data():
    global current_speed,current_flow
    data = {
        'speed': current_speed,  # 车速范围20-80km/h
        'flow': current_flow   # 车流量范围50-200辆/小时
    }
    return jsonify(data)

@app.route('/prediction')
def get_pre_data():
    global pre_time,pre_speed,pre_flow,pre_rank
    data = {
        'time': pre_time,
        'speed': round(pre_speed,2),
        'flow': round(pre_flow*2,2),
        'congestion': pre_rank
    }
    return jsonify(data)

@app.route('/map')
def get_map_data():
    global pre_rank
    rank = [pre_rank]  # 这里使用简化的数据

    data = {
        'rank': rank
    }

    return jsonify(data)


@app.route('/history')
def get_history_data():
    # 生成12个历史时间点的数据
    times = []
    speed_data = []
    flow_data = []

    current_time = datetime(day=10,hour=0,minute=0,second=0,year=2024,month=10)

    for i in range(24):
        # 生成时间点（每5分钟一个点）
        time_point = current_time - timedelta(hours=i)
        times.insert(0, time_point.strftime('%H:%M'))

        # 生成随机数据
        speed = random.randint(20, 80)  # 车速范围20-80km/h
        flow = random.randint(50, 200)  # 流量范围50-200辆/小时

        speed_data.insert(0, speed)
        flow_data.insert(0, flow)

    data = {
        'times': times,
        'speed': speed_data,
        'flow': flow_data
    }

    return jsonify(data)


if __name__ == '__main__':
    app.run(debug=True)
    # update_congestion(1672531200,2)
    # update_flow(1672531200, 167)
    # update_speed(1672531200, 65)speed_dict
    # write_ini(config,'speed_dict',{'01-02 08:00:00': 66})
    # write_ini(config, 'flow_dict', {'01-02 08:00:00': 160})
    # write_ini(config,'svr_data',init_data('svr_data'))
    # write_ini(config, 'lstm_data', init_data('lstm_data'))